package org.example.repository.impl;

import jakarta.annotation.Resource;
import org.example.model.Form;
import org.example.repository.FormRepository;
import com.mongodb.client.result.UpdateResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

@Component
public class FormRepositoryImpl implements FormRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 创建对象
     *
     * @param
     */
    @Override
    public void saveForm(Form form) {
        mongoTemplate.save(form,form.getFormName());
    }

    /**
     * 根据用户名查询对象
     *
     * @param
     * @return
     */
    @Override
    public Form findFormByFormName(String formName) {
        Query query = new Query(Criteria.where("formName").is(formName));
        Form form = mongoTemplate.findOne(query, Form.class, formName);
        return form;
    }

    /**
     * 更新对象
     *
     * @param
     */
    @Override
    public long updateForm(Form form) {
        Query query = new Query(Criteria.where("formName").is(form.getFormName()));
        Update update = new Update().set("rules", form.getRules()).set("options", form.getOptions());
        //更新查询返回结果集的第一条
        UpdateResult result = mongoTemplate.updateFirst(query, update, Form.class,form.getFormName());
        // 更新查询返回结果集的所有
        // mongoTemplate.updateMulti(query,update,UserEntity.class);
        if (result != null) {
            return result.getMatchedCount();
        } else {
            return 0;
        }
    }



    /**
     * 删除对象
     *
     * @param
     */
    @Override
    public void deleteFormByNmae(String formName) {
        Query query = new Query(Criteria.where("formName").is(formName));
        mongoTemplate.remove(query, Form.class,formName);
    }
}
